package com.tdam2014.grupo3.adapters;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.tdam2014.grupo3.R;
import com.tdam2014.grupo3.entities.Photo;
import com.tdam2014.grupo3.flickr.util.URLUtils;
import com.tdam2014.grupo3.tasks.ImageDownloadTask;
import com.tdam2014.grupo3.utils.ImagesUtils;

public class PhotoAdapter extends BaseAdapter {
	
	private LayoutInflater inflater;
	private ArrayList<Photo> photos;
	
	private String photoSetID;
	
	public PhotoAdapter(Context context) {
		this.inflater = LayoutInflater.from(context);
	}

	public void setPhotoSetID(String photoSetID) {
		this.photoSetID = photoSetID;
	}

	public void setPhotos(ArrayList<Photo> photo) {
		this.photos = photo;
	}

	@Override
	public int getCount() {
		return photos.size();
	}

	@Override
	public Photo getItem(int position) {
		return photos.get(position);
	}

	@Override
	public long getItemId(int position) {
		return -1;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View item = null;
		HolderPhotoItemGrid holder = null;
		
//		if(convertView == null) {
			item = inflater.inflate(R.layout.photo_grid_item, null);
			holder = new HolderPhotoItemGrid();
			holder.image = (ImageView) item.findViewById(R.id.imgPhotoImage);
			holder.title = (TextView) item.findViewById(R.id.txtPhotoTitle);
			holder.posted = (TextView) item.findViewById(R.id.txtPhotoPosted);
			holder.comments = (TextView) item.findViewById(R.id.txtPhotoComments);
//			item.setTag(holder);
//		} else {
//			item = convertView;
//			holder = (HolderPhotoItemGrid) item.getTag();
//		}
		
		Photo photo = photos.get(position);
		
//		File thumbImage = new File(Images.THUMBS_PATH + photoSetID + "_" + photo.getId() + ".jpg");
//		if(thumbImage.exists()) {
//			holder.image.setImageBitmap(BitmapFactory.decodeFile(thumbImage.getAbsolutePath()));
//		}
		
		File thumbImage = new File(ImagesUtils.THUMBS_PATH + photoSetID + "_" + photo.getId() + ".jpg");
		if(thumbImage.exists()) holder.image.setImageBitmap(BitmapFactory.decodeFile(thumbImage.getAbsolutePath()));
		else {
			ImageDownloadTask tImageDownloadTask = new ImageDownloadTask(holder.image, false, photoSetID, photo.getId());
			tImageDownloadTask.execute(URLUtils.getImageUrl(photo.getFarm(), photo.getServer(), photo.getId(), photo.getSecret(), URLUtils.SQUARE_150_IMAGE_SUFFIX));
		}
		
		holder.title.setText(photo.getTitle());
		holder.posted.setText(photo.getDatePostedDateTime());
		holder.comments.setText(String.valueOf(photo.getCountComments()));

		return item;
	}
	
	private class HolderPhotoItemGrid {
		ImageView image;
		TextView title;
		TextView posted;
		TextView comments;
	}
}
